package shopping.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shopping.demo.code.ResponseCode;
import shopping.demo.entities.Goods;
import shopping.demo.entities.response.Response;
import shopping.demo.service.GoodsService;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping("/list")
    public String findAll() {
        List<Goods> goods = goodsService.FindAll();
        return JSON.toJSONString(goods);
    }

    @PostMapping(value = "/good", consumes = "application/json")
    public String insertGoods(@RequestBody JSONObject jsonObject) throws Exception{
        Goods goods = JSONObject.parseObject(jsonObject.toJSONString(),Goods.class);
        goodsService.insertGoods(goods);
        return JSONObject.toJSONString(new Response(ResponseCode.GOODS_SUCCESS.getCode(),ResponseCode.GOODS_SUCCESS.getMsg()));
    }

    @DeleteMapping(value = "/good",consumes = "application/json")
    public String deleteById(@RequestBody JSONObject jsonObject) throws Exception{
        Integer id = jsonObject.getInteger("id");
        goodsService.DeleteById(id);
        return JSONObject.toJSONString(new Response(ResponseCode.GOODS_SUCCESS.getCode(),ResponseCode.GOODS_SUCCESS.getMsg()));

    }

    @PatchMapping(value = "/good",consumes = "application/json")
    public String changePrice(@RequestBody JSONObject jsonObject) throws Exception{
        Integer id = jsonObject.getInteger("id");
        Integer price = jsonObject.getInteger("price");
        goodsService.changePrice(id, price);
        return JSONObject.toJSONString(new Response(ResponseCode.GOODS_SUCCESS.getCode(),ResponseCode.GOODS_SUCCESS.getMsg()));
    }

}
